<template>
  <div>
    <div class="card" style="margin-bottom: 10px">
      <el-input v-model="data.name" style="width:20%;border: none;border-radius: 5px ;margin-right: 10px"
                class="w-50 m-2" placeholder="作者姓名" :prefix-icon="Search"/>
      <el-input v-model="data.username" style="width:20%;border-radius: 5px ;margin-right: 10px" class="w-50 m-2" placeholder="发布者账号" :prefix-icon="Search"/>
      <el-button type="primary" round style="margin-left: 10px" @click="load">查询</el-button>
      <el-button type="info" round @click="reset" style="margin-left: 10px">清除</el-button>
      <el-button type="primary" v-if="user.role==='ADMIN'" round @click="handleAdd">添加</el-button>
      <el-button type="danger" round @click="reset" >刷新</el-button>
    </div>
    <div class="card" style="margin-bottom: 10px;">
      <el-table :data="data.tableData" style="width: 100%">
        <el-table-column prop="id" label="序号"/>
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="content" label="内容" />
        <el-table-column prop="time" label="上传时间"  />
        <el-table-column prop="username" label="账号名" />
        <el-table-column >
          <template #default="scope" >
            <el-button type="primary" style="margin-right: 10px;margin-bottom: 3px" @click="editHandler(scope.row)">编辑</el-button>
            <el-button type="danger"  style="margin-left: 0px" @click="delHandler(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-pagination v-model:current-page="data.pageNum" v-model:page-size="data.pageSize"
                     @current-change = "handleCurrentChange"
                     layout="prev, pager, next" :total="data.total"
      />
    </div>
    <el-dialog v-model="data.formVisible" title="添加信息" width="40%">
      <el-form :model="data.form" :rules="rules" ref="formRef" label-width="100px" label-position="right" >
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="data.form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
              v-model="data.form.content"
              :autosize="{ minRows: 1, maxRows: 10 }"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible=false">关闭</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive,ref} from "vue";
import {Search } from '@element-plus/icons-vue'
import request from "@/utils/request";
import router from "../../router";
import {ElMessage, ElMessageBox} from "element-plus";

const user=JSON.parse(localStorage.getItem("student-user"))
const formRef=ref();
const handleCurrentChange = ()=>{
  load()
}

const data = reactive({
  name:'',
  number: '',
  username: '',
  tableData:[],
  total: 0,
  pageNum: 1, //当前的页码
  pageSize: 10, // 每页个数
  formVisible: false,
  form: {}
})

const  load =() =>{
  request.get("/article/select", {
    params:{
      pageNum: data.pageNum,
      pageSize:data.pageSize,
      name: data.name,
      username: data.username,
    }} ).then(res => {
    data.tableData = res.data?.list || []
    data.total = res.data?.total || 0
  })
}
const reset=() => {
  data.name = ''
  data.number = ''
  data.teacher = ''
  load()
}
const  handleAdd=()=>{
  data.form={}
  data.formVisible=true
}
const  rules = reactive({
  name:[
    {required: true,message:'请输入姓名',trigger:'blur'},
  ],
  title:[
    {required: true,message:'请输入标题',trigger:'blur'},
  ],
  content:[
    {required: true,message:'请输入内容',trigger:'blur'},
  ],
})
const  save =() =>{
  formRef.value.validate((valid)=> {
    data.form.name='ADMIN'
    const now = new Date();
    data.form.time = now.toLocaleString();
    data.form.username=user.username;
    if (valid)
    {
      request.request({
        url: data.form.id ? '/article/update' : '/article/add',
        method: data.form.id ? 'PUT' : 'POST',
        data: data.form
      }).then(res => {
        if (res.code === '200') {
          load()
          data.formVisible = false
          ElMessage.success('操作成功')
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const editHandler=(row)=>{
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}
const delHandler=(id)=>{
  ElMessageBox.confirm(
      '此操作会永久删除数据，是否确认?',
      '注意！',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        request.delete('/article/delete/'+ id).then(res=>{
          if(res.code==='200'){
            load()
            ElMessage.success('删除成功')
          } else{
            ElMessage.error(res.msg)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}
load()
</script>
<style>
.cell{
  word-wrap: break-word;
  display: -webkit-box;
  -webkit-line-clamp: 8;
  -webkit-box-orient: vertical;
}
</style>